<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:insert="common/header :: head"></head>
<style>
  .up-file input {
    position: absolute;
    font-size: 100px;
    right: 0;
    top: 0;
    opacity: 0;
    filter: alpha(opacity=0);
    cursor: pointer;
  }
</style>
<body>
<div id="wrapper" v-cloak>
  <div>
    <el-input size="small" v-model="search" style="width: 20%;" suffix-icon="el-icon-search"
              placeholder="请输入工号或姓名搜索"></el-input>
    <el-select size="small" @click.native="AllRole" @change="change" v-model="selectRole.role" placeholder="通过角色进行筛选"
               value-key="name">
      <el-option value="全部">全部</el-option>
      <el-option v-for="role in selectRole" :value=role :label="role.name">
      </el-option>
    </el-select>
    <el-button size="small" @click="SeLoadTable" type="primary" style="margin: 10px 0">查询</el-button>

    <el-button size="small" @click="add" type="primary" style="margin: 10px 0">新增</el-button>
    <el-button size="small" type="primary" @click="[sedialogFormVisible = true]">批量添加</el-button>
    <el-button size="small" type="primary">
      <a href="../api/user/downLoadTemplate" style="color: white; display: block;">下载模板</a>
    </el-button>
  </div>
  <el-label style="color: red;"> 批量添加请在左侧下载模板并通过模板上传</el-label>
  <div style="margin-top: -18px;">
    <el-divider></el-divider>
  </div>

  <el-dialog title="批量添加系统用户" :visible.sync="sedialogFormVisible" width="30%" height="110%">
    <el-form style="display: inline-block;margin-left: 30px">
      <el-upload class="upload-demo" ref="upload" multiple accept=".xls"
                 action="" :auto-upload="false" :show-file-list="true" :on-success="endUpload" :on-error="errorUp"
                 :before-upload="beforeUpload" :http-request="uploadFile">
        <el-button size="small" slot="trigger" type="primary">选择文件</el-button>
        <div slot="tip">请上传文件大小不超过2MB,格式为 .xls类型的文件</div>
      </el-upload>
    </el-form>
    <p style="margin-top: 20px;">请先下载模板文件填写再上传，且一次只能上传一个文件。</p>
    <div slot="footer" class="dialog-footer" style="display: flex">
      <el-button size="small" type="primary" @click="submitUploadList">确 定</el-button>
      <el-button size="small" @click="sedialogFormVisible = false">取 消</el-button>
    </div>
  </el-dialog>

  <el-dialog title="所属学院(部门)" :visible.sync="departmentDialog" :lock-scroll="true" :close-on-click-modal="false"
             :close-on-press-escape="false">
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="类别">
        <el-radio-group v-model="form.resource">
          <el-radio label="学院" @change="find"></el-radio>
          <el-radio label="部门" @change="find"></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-select v-model="form.name" placeholder="请选择">
          <el-option v-for="item in value" :label="v.form.resource==='学院'?item.udName:item.tname"
                     :value="v.form.resource==='学院'?item.udId:item.tid"
                     :key="v.form.resource==='学院'?item.udId:item.tid"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-tooltip class="item" content="清除该角色的所属关系" placement="bottom">
        <el-button type="primary" @click="resetDep">重置</el-button>
      </el-tooltip>
      <el-button type="primary" @click="changeDep">确定</el-button>
      <el-button @click="departmentDialog = false">取 消</el-button>
    </div>
  </el-dialog>


  <el-table v-loading="loading" :data="tableData" border style="width: 100%">
    <el-table-column prop="id" label="ID" width="150" sortable></el-table-column>
    <el-table-column prop="username" placeholder="请输入工号" label="工号" width="150"></el-table-column>
    <el-table-column prop="nickname" placeholder="请输入姓名" label="姓名" width="120"></el-table-column>
    <el-table-column prop="phone" placeholder="请输入电话" label="电话" width="150"></el-table-column>
    <el-table-column label="角色" width="200">
      <template slot-scope="scope">
        <el-select size="small" v-model="scope.row.roles" value-key="id" multiple placeholder="请选择"
                   @change="changeRole(scope.row)">
          <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </template>
    </el-table-column>
    <el-table-column prop="colAdep" placeholder="所属学院(部门)" label="所属学院(部门)" width="200"></el-table-column>
    <!--<el-table-column label="所属学院(部门)" prop="colAdep" width="200">
          <template slot-scope="scope">
             <el-link type="primary" @click="changeRedio(scope.row)">
               {{ scope.row|rowFilter }}
             </el-link>
           </template>
    </el-table-column>-->
    <el-table-column fixed="right" label="操作">
      <template slot-scope="scope">
        <el-button size="mini" type="primary" @click="edit(scope.row)" icon="el-icon-edit"></el-button>
        <el-button size="mini" type="warning" style="margin-right: 10px;" @click="handlePwd(scope.row)"
                   icon="el-icon-refresh">密码重置
        </el-button>
        <el-popconfirm @onConfirm="del(scope.row.id)" title="确定删除？">
          <el-button size="mini" type="danger" icon="el-icon-delete" slot="reference"></el-button>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页 -->
  <div style="background-color: white; padding: 10px 0">
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>
  </div>

  <el-dialog title="用户信息" :visible.sync="dialogFormVisible" width="40%"
             :lock-scroll="true" :close-on-click-modal="false"
             :close-on-press-escape="false" @close="resetForm('userRef')">
    <el-form :model="tempUser" ref="userRef" :rules="userRef">
      <el-form-item label="工号" label-width="100px" prop="username">
        <el-input placeholder="请输入工号" v-model="tempUser.username" autocomplete="off" style="width: 80%"></el-input>
      </el-form-item>
      <el-form-item label="姓名" label-width="100px">
        <el-input placeholder="请输入姓名" v-model="tempUser.nickname" autocomplete="off" style="width: 80%"></el-input>
      </el-form-item>

      <el-form-item label="电话" label-width="100px" prop="phone">
        <el-input placeholder="请输入电话" v-model="tempUser.phone" autocomplete="off" style="width: 80%"></el-input>
      </el-form-item>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" type="primary" @click="saveAdd('userRef')">确 定</el-button>
      <el-button size="small" @click="cancel()">取 消</el-button>
    </div>
  </el-dialog>
  <el-dialog title="用户信息" :visible.sync="ThdialogFormVisible" width="40%"
             :lock-scroll="true" :close-on-click-modal="false"
             :close-on-press-escape="false" @close="resetForm('userRef')">
    <el-form :model="tempUser" ref="userRef" :rules="userRef">
      <el-form-item label="工号" label-width="100px" prop="username">
        <el-input placeholder="请输入工号" v-model="tempUser.username" onfocus=this.blur() autocomplete="off"
                  style="width: 80%"></el-input>
      </el-form-item>
      <el-form-item label="姓名" label-width="100px">
        <el-input placeholder="请输入姓名" v-model="tempUser.nickname" autocomplete="off" style="width: 80%"></el-input>
      </el-form-item>

      <el-form-item label="电话" label-width="100px" prop="phone">
        <el-input placeholder="请输入电话" v-model="tempUser.phone" autocomplete="off" style="width: 80%"></el-input>
      </el-form-item>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" type="primary" @click="MyUpdate('userRef')">确 定</el-button>
      <el-button size="small" @click="cancel()">取 消</el-button>
    </div>
  </el-dialog>
<!--  <el-dialog title="工作量曲线图" :visible.sync="dialogVisible" :close-on-press-escape="false"-->
<!--             :close-on-click-modal="true" :show-close="true" >-->
<!--    <div id="Echarts" style="width: 700px; height: 400px;"  ></div>-->
<!--  </el-dialog>-->

</div>
<script type="text/javascript" th:src="@{/js/tinymce/tinymce.min.js}"></script>
<script th:src="@{/js/echarts.min.js}"></script>
<script type="text/javascript">
  var UserSaveBtn = true;
  let urlBase = "../api/user/";
  var v = new Vue({
    el: "#wrapper",
    data: {
      var: checkUserId = (rule, value, callback) => {
        if (!value) {
          callback(new Error('工号不能为空'))
        } else {
          callback()
          /*const regCN = /^[0-9]{10}$/
          if (!regCN.test(value)) {
            callback(new Error('工号只能为10位数字'))
          } else {
            callback()
          }*/
        }
      },
      var: checkMobile = (rule, value, callback) => {
        if (!value) {
          callback(new Error('手机号不能为空'))
        } else {
          if (isNaN(value)) {
            callback(new Error('手机号码只能为数字'))
          }
          const regCN = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
          if (!regCN.test(value)) {
            callback(new Error('手机号格式不正确'))
          } else {
            callback()
          }
        }
      },
      loading: true,
      fileList: {},
      user: {},
      tableData: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      dialogFormVisible: false,
      entity: {},
      ThdialogFormVisible: false,
      sedialogFormVisible: false,
      isCollapse: false,
      search: '',
      options: [],
      props: [{"label": "用户名", "prop": "username"}, {"label": "电话", "prop": "phone"}],
      tempUser: {
        username: '',
        phone: '',
        nickname: ''
      },
      userRef: {
        username: [
          {validator: checkUserId, trigger: 'blur'}
        ]/*,
                phone: [
                    {validator: checkMobile, trigger: 'blur'}
                ]*/
      },
      temp: '',
      //设置部门
      form: {
        name: '',
        resource: '',
      },
      value: '',
      college: [],
      department: [],
      departmentDialog: false,
      selectRole: [],
      roleId: '',
      // dialogVisible:false
    },
    created() {
      this.user = sessionStorage.getItem("user") ? JSON.parse(sessionStorage.getItem("user")) : {};
      this.loadTable();
    },
    filters: {
      rowFilter: function (value) {
        if (value.udid === null && value.tid === null) {
          return '修改学院（部门）';
        } else if (value.udid !== null) {
          return v.collegeFilter(value.udid);
        } else if (value.tid !== null) {
          return v.departmentFilter(value.tid);
        }
      }
    },
    methods: {
      change(e) {
        this.roleId = e.id
      },
      // showDialog() {
      //   this.dialogVisible = true;
      //   // 在弹出框显示时调用drawChart函数
      //   this.$nextTick(() => {
      //     this.drawChart();
      //   });
      // },
      // drawChart() {
      //   // 获取 ECharts 容器元素
      //   const chartContainer = document.getElementById("Echarts");
      //   // 初始化 ECharts 实例
      //   const myChart = echarts.init(chartContainer);
      //   // 设置图表的配置项和数据
      //   const option = {
      //     title: {
      //       text: '工作量曲线图',
      //     },
      //     xAxis: {
      //       type: 'category',
      //       data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
      //     },
      //     yAxis: {
      //       type: 'value',
      //       min:0
      //     },
      //     series: [{
      //       data: [150, 230, 224, 218, 135, 147, 260],
      //       type: 'line',
      //     }],
      //   };
      //   // 使用配置项和数据绘制图表
      //   myChart.setOption(option);
      // },
      // 解析模板
      async uploadFile(param) {
        const File = param.file;
        const service = axios.create({})
        let formData = new FormData()
        formData.append("file", File);
        this.$message({message: "数据添加中请稍后!", type: "warning",duration:2000});
        const res = await service({
          url: urlBase + 'file/upload',
          method: 'POST',
          transformRequest: [function (data, headers) {
            // 去除post请求默认的Content-Type
            delete headers.post['Content-Type']
            return data
          }],
          data: formData
        }).then(res => {
          if (res.data.code == 1) {
            this.loadTable();
            this.sedialogFormVisible = false;
            this.$message({message: '上传成功', type: "success",duration:2000});
            this.$refs.upload.clearFiles ()
          } else {
            this.$message({showClose: true, duration: 10000, message: res.data.msg, type: "error"});
            this.$refs.upload.clearFiles ()
          }
        })
      },
      AllRole(e) {
        $.ajax({url: "../api/role/allrole", type: "GET",}).then(res => {
          this.selectRole = res.data
        })
      },
      //before-upload 上传文件前
      beforeUpload: function (file) {
        if (['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'].indexOf(file.type) == -1 && ['application/vnd.ms-excel'].indexOf(file.type) == -1) {
          this.$message.error({message: "请上传.xls格式的文件", type: 'error'});
          return false;
        }
      },
      //上传失败调用
      errorUp(err) {
        this.$message({message: err, type: "error"})
      },
      //上传成功调用
      endUpload() {
        this.loadTable()
      },
      //提交后跳转到:http-request
      submitUploadList() {
        const files = this.$refs.upload.uploadFiles;
        let size2M = files[0].size / 1024 / 1024 < 2;
        if (!size2M) {
          this.$message.warning('上传大小不能超过2M!');
          return false;
        }

        if (files >= 0) {
          this.$message({message: "请选择文件后再点确定", type: "warning",duration:2000})
        } else {
          this.$refs.upload.submit()
        }
      },
      changeRole(row) {
        row.role = row.roles
        this.entity = JSON.parse(JSON.stringify(row));
        this.entity.roles = "";
        this.save();
      },
      //部门修改框中select框定位
      changeRedio(value) {
        this.departmentDialog = true;
        this.temp = value;
        if (value.udid !== null) {
          this.form.resource = "学院";
          this.find(this.form.resource);
        } else if (value.tid !== null) {
          this.form.resource = "部门";
          this.find(this.form.resource);
        } else {
          this.form.resource = "";
        }
      }, changeDep() {
        if (v.form.resource === "学院") {
          this.temp.udid = v.form.name;
          this.temp.tid = null;
          this.entity = JSON.parse(JSON.stringify(this.temp));
          $.ajax({
            url: urlBase + "dUpdate",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify(this.entity)
          }).then(res => {
            if (res.code == 1) {
              this.$message({message: "保存成功", type: "success",duration:2000});

              v.tempUser.username = "";
              v.tempUser.nickname = "";
              v.tempUser.phone = "";
              this.form.name = "";
              this.form.resource = "";
              this.departmentDialog = false;
              this.loadTable();
            } else {
              this.$message({message: res.msg, type: "error"})
            }
          })
        } else if (v.form.resource === "部门") {
          this.temp.tid = v.form.name;
          this.temp.udid = null;
          this.entity = JSON.parse(JSON.stringify(this.temp));
          $.ajax({
            url: urlBase + "dUpdate",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify(this.entity)
          }).then(res => {
            if (res.code == 1) {
              this.$message({message: "保存成功", type: "success",duration:2000});
              v.tempUser.username = "";
              v.tempUser.nickname = "";
              v.tempUser.phone = "";
              this.form.name = "";
              this.form.resource = "";
              this.departmentDialog = false;
              this.loadTable();
            } else {
              this.$message({message: res.msg, type: "error"})
            }
          })
        }
      }, resetDep() {
        this.form.name = null;
        this.form.resource = null;
        this.temp.udid = null;
        this.temp.tid = null;
        this.entity = JSON.parse(JSON.stringify(this.temp));
        this.save();
      }, handleCollapse() {
        this.isCollapse = !this.isCollapse;
      }, logout() {
        // 请求退出接口
        $.get(urlBase + "logout");
        localStorage.removeItem("user");
        location.href = "../login";
      }, SeLoadTable() {
        this.pageNum = 0;
        this.loadTable();
      }, loadTable() {
        $.get("../api/udp/findAll").then(res => {
          this.college = res.data;
        })
        $.get(urlBase + "page?pageNum=" + this.pageNum + "&pageSize=" + this.pageSize + "&name=" + this.search + "&role=" + this.roleId).then(res => {
          if (res.code == 1){
            this.selectRole = {}
            this.tableData = res.data.records;
            this.tableData.forEach(data=>{
              data.colAdep = this.college[0].udname;
              if (data.roles){
                data.roles = data.roles.replaceAll(/[\[\]]/g, "")
                data.roles = data.roles.split(",");
                data.roles = data.roles.map(Number)
                if (data.roles == 0){
                  data.roles = null;
                }
              }
            })
            this.$message({message: "查询成功", type: "success",duration:2000});
            this.total = res.data.total;
          }else {
            this.$message({message: "查询失败，暂无信息", type: "warning",duration:2000});
          }

        })
        $.get("../api/role").then(res => {
          this.options = res.data;
        });
        //$.get("../api/labelDept").then(res => {this.department = res.data;})
        this.loading = false;
      }, find(value) {
        if (value === "学院") {
          this.form.name = '';
          this.value = this.college;
          let values = v.$data.college;
          let id = this.temp.udid;
          for (let i = 0; i < values.length; i++) {
            if (id === values[i].udId) {
              this.form.name = values[i].udId;
            }
          }
        } else if (value === "部门") {
          this.form.name = '';
          this.value = this.department;
          let id = this.temp.tid;
          let values = v.$data.department;
          for (let i = 0; i < values.length; i++) {
            if (id === values[i].tid) {
              this.form.name = values[i].tid;
            }
          }
        }
      }, collegeFilter(value) {
        let values = v.$data.college;
        if (value === null) {
          $('#dept').hide();
          return '修改所属学院（部门）';
        } else {
          $('#college').show();
          for (let i = 0; i < values.length; i++) {
            if (value === values[i].udId) {
              $('#dept').hide();
              return values[i].udName;
            }
          }
        }
      }, departmentFilter(value) {
        let values = v.$data.department;
        if (value === null) {
          $('#college').hide();
          return '修改所属学院（部门）';
        } else {
          $('#dept').show();
          for (let i = 0; i < values.length; i++) {
            if (value === values[i].tid) {
              $('#college').hide();
              return values[i].tname;
            }
          }
        }
      }, exp() {
        window.open(urlBase + "/export");
      }, handleSizeChange(pageSize) {
        this.pageSize = pageSize;
        this.loadTable();
      }, handleCurrentChange(pageNum) {
        this.pageNum = pageNum;
        this.loadTable();
      }, add() {
        this.tempUser = {};
        this.dialogFormVisible = true;
        UserSaveBtn = true
      }, saveAdd(formName) {
        v.$refs[formName].validate((valid) => { //校检表单
          if (valid) {
            this.entity.username = v.tempUser.username;
            this.entity.nickname = v.tempUser.nickname.replace(/\s*/g, "");
            this.entity.phone = v.tempUser.phone;
            this.save();
          }
        });
      }, cancel() {
        this.dialogFormVisible = false
        this.ThdialogFormVisible = false
      }, MyUpdate(formName) {
        if (UserSaveBtn) {
          UserSaveBtn = false
          v.$refs[formName].validate((valid) => { //校检表单
            if (valid) {
              this.entity.username = v.tempUser.username;
              this.entity.nickname = v.tempUser.nickname.replace(/\s*/g, "");
              this.entity.phone = v.tempUser.phone;
            }
          });
          let params = new URLSearchParams();
          params.append("username", this.entity.username);
          params.append("nickname", this.entity.nickname);
          if (this.entity.phone != null) {
            params.append("phone", this.entity.phone);
          }
          if (this.entity.username == null || this.entity.nickname == null) {
            this.$message({
              message: "提交的信息有误，请检测后再提交",
              type: "warning",duration:2000
            })
          } else {
            axios.post(urlBase + 'updateinfo', params).then(res => {
              if (res.status === 200) {
                this.entity.username = null
                this.entity.nickname = null
                this.entity.phone = null
                this.ThdialogFormVisible = false
                this.loadTable()
                this.$message({message: "修改成功", type: "success",duration:2000})
              } else {
                UserSaveBtn = true
              }
            })
          }
        }
      }, save() {
        if (UserSaveBtn) {
          UserSaveBtn = false
          let type = this.entity.id ? "dUpdate" : "save";
          $.ajax({
            url: urlBase + type,
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify(this.entity)
          }).then(res => {
            if (res.code == 1) {
              this.$message({message: "保存成功", type: "success",duration:2000});
              v.tempUser.username = "";
              v.tempUser.nickname = "";
              v.tempUser.phone = "";
              this.form.name = "";
              this.form.resource = "";
              this.loadTable();
              UserSaveBtn = true
            } else {
              UserSaveBtn = true
              this.$message({message: res.msg, type: "error",duration:2000})
            }
            this.departmentDialog = false;
            this.dialogFormVisible = false;
          })
        }
      }, resetForm(formName) {
        this.$refs[formName].resetFields();
      }, edit(obj) {
        this.tempUser = JSON.parse(JSON.stringify(obj));
        this.ThdialogFormVisible = true;
        UserSaveBtn = true
      }, del(id) {
        $.ajax({
          url: urlBase + "del/" + id,
          type: "GET"
        }).then(res => {
          if (res.code == 1) {
            this.$message({message: "删除成功", type: "success",duration:2000})
            this.loadTable();
          } else {
            this.$message({message: res.msg, type: "error"})
          }
        })
      }, handlePwd(obj) {
        this.$confirm('确定重置 ' + obj.nickname + ' 的密码吗,重置后密码为工号', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let params = new URLSearchParams();
          params.append("username", obj.username);
          axios.post(urlBase + 'resettingPwd', params).then(res => {
            if (res.data.code == 1) {
              this.$message({message: "重置成功!", type: "success",duration:2000})
            } else {
              this.$message.error(res.data.msg);
            }
          })
        }).catch(() => {
          this.$message({type: 'info', message: '已取消',duration:2000});
        });
      }
    }
  })
</script>
</body>
</html>
